<template>
  <div class="carousel-config-panel">
    <h2 class="panel-title">轮播图配置</h2>
    <a-form layout="vertical">
      <a-form-item label="配置场景">
        <a-select v-model:value="currentScene" @change="handleSceneChange">
          <a-select-option value="home">首页轮播图</a-select-option>
          <a-select-option value="anime">二次元轮播图</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="自动播放">
        <a-switch v-model:checked="configOptions.autoplay" />
      </a-form-item>

      <a-form-item label="播放速度 (毫秒)">
        <a-slider
          v-model:value="configOptions.autoplaySpeed"
          :min="1000"
          :max="10000"
          :step="500"
        />
        <div class="slider-value">{{ configOptions.autoplaySpeed }}ms</div>
      </a-form-item>

      <a-form-item label="显示指示点">
        <a-switch v-model:checked="configOptions.dots" />
      </a-form-item>

      <a-form-item label="切换效果">
        <a-select v-model:value="configOptions.effect">
          <a-select-option value="scrollx">水平滚动</a-select-option>
          <a-select-option value="fade">淡入淡出</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="轮播项">
        <div v-for="(item, index) in carouselItems" :key="index" class="carousel-item-config">
          <a-card class="item-card">
            <template #title>
              <div class="item-header">
                <span>轮播项 {{ index + 1 }}</span>
                <a-button
                  type="text"
                  danger
                  @click="removeCarouselItem(index)"
                  v-if="carouselItems.length > 1"
                >
                  <delete-outlined />
                </a-button>
              </div>
            </template>

            <a-form-item label="图片URL">
              <div class="image-upload-wrapper">
                <a-input v-model:value="item.imageUrl" />
                <a-upload
                  name="file"
                  :showUploadList="false"
                  :beforeUpload="(file) => beforeUpload(file, index)"
                  @change="(info) => handleImageChange(info, index)"
                >
                  <a-button type="primary" size="small">
                    <template #icon><upload-outlined /></template>
                    上传图片
                  </a-button>
                </a-upload>
              </div>
              <div class="image-preview" v-if="item.imageUrl">
                <img :src="item.imageUrl" alt="轮播图预览" />
              </div>
            </a-form-item>

            <a-form-item label="标题">
              <a-input v-model:value="item.title" />
            </a-form-item>

            <a-form-item label="描述">
              <a-textarea v-model:value="item.description" :rows="2" />
            </a-form-item>

            <a-form-item label="按钮文本">
              <a-input v-model:value="item.buttonText" />
            </a-form-item>

            <a-form-item label="按钮链接">
              <a-input v-model:value="item.buttonLink" />
            </a-form-item>
          </a-card>
        </div>

        <a-button type="dashed" block @click="addCarouselItem" class="add-item-btn">
          <plus-outlined /> 添加轮播项
        </a-button>
      </a-form-item>

      <a-form-item>
        <a-space>
          <a-button type="primary" @click="saveConfig">保存配置</a-button>
          <a-button @click="resetConfig">重置</a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, defineEmits, defineProps, watch } from 'vue'
import { message } from 'ant-design-vue'
import { DeleteOutlined, PlusOutlined, UploadOutlined } from '@ant-design/icons-vue'
import {
  getCarouselConfig,
  saveCarouselConfig,
  updateCarouselItem as updateCarouselItemApi,
  addCarouselItem as addCarouselItemApi,
  deleteCarouselItem as deleteCarouselItemApi,
  listCarouselItems as listCarouselItemsApi,
  updateCarouselItemSort as updateCarouselItemSortApi,
  uploadCarouselImage,
} from '../api/carouselController'
import '../api/typings.d.ts'

// 定义组件需要使用的类型
interface CarouselConfigData {
  autoplay?: boolean
  autoplaySpeed?: number
  dots?: boolean
  effect?: string
}

interface CarouselItem {
  id?: number
  scene?: string
  imageUrl?: string
  title?: string
  description?: string
  buttonText?: string
  buttonLink?: string
  sort?: number
  status?: number
}

interface CarouselConfigDTO {
  config?: CarouselConfigData
  items?: CarouselItem[]
}

// 定义组件属性
const props = defineProps({
  initialConfig: {
    type: Object as () => CarouselConfigData,
    default: () => ({
      autoplay: true,
      autoplaySpeed: 3000,
      dots: true,
      effect: 'scrollx',
    }),
  },
  initialItems: {
    type: Array as () => CarouselItem[],
    default: () => [],
  },
  initialScene: {
    type: String,
    default: 'home',
  },
})

// 定义事件
const emit = defineEmits(['update:config', 'update:items', 'update:scene'])

// 当前选中的场景
const currentScene = ref(props.initialScene)

// 配置选项
const configOptions = reactive<CarouselConfigData>({
  autoplay: props.initialConfig.autoplay,
  autoplaySpeed: props.initialConfig.autoplaySpeed,
  dots: props.initialConfig.dots,
  effect: props.initialConfig.effect,
})

// 轮播项数据
const carouselItems = ref<CarouselItem[]>(
  props.initialItems.length > 0
    ? [...props.initialItems]
    : [
        {
          imageUrl: 'https://hlp-lc99-1323942529.cos.ap-chongqing.myqcloud.com/carousel/ai-1.jpg',
          title: '自然风光',
          description: '探索大自然的壮丽景色',
          buttonText: '了解更多',
          buttonLink: '#',
        },
      ]
)

// 监听配置变化
watch(
  configOptions,
  (newValue) => {
    emit('update:config', { ...newValue })
  },
  { deep: true }
)

// 监听轮播项变化
watch(
  carouselItems,
  (newValue) => {
    emit('update:items', [...newValue])
  },
  { deep: true }
)

// 添加轮播项
const addCarouselItem = () => {
  carouselItems.value.push({
    imageUrl: 'https://hlp-lc99-1323942529.cos.ap-chongqing.myqcloud.com/carousel/ai-1.jpg',
    title: '新轮播项',
    description: '请添加描述',
    buttonText: '点击按钮',
    buttonLink: '#',
    scene: currentScene.value,
  })
}

// 删除轮播项
const removeCarouselItem = (index: number) => {
  carouselItems.value.splice(index, 1)
}

// 保存配置到后端
const saveConfig = async () => {
  try {
    // 确保所有轮播项都有场景属性
    carouselItems.value.forEach((item) => {
      item.scene = currentScene.value
    })

    // 尝试调用后端API保存配置
    try {
      const res = await saveCarouselConfig(
        {
          config: configOptions,
          items: carouselItems.value,
        },
        { scene: currentScene.value }
      )

      if (res.data && res.data.code === 0) {
        message.success('配置保存成功')
        return
      }
    } catch (error) {
      console.warn('后端API未实现，模拟保存成功响应', error)
      // 模拟保存成功
      message.success('配置已保存（本地模拟）')
      // 存储到本地存储，便于演示
      try {
        localStorage.setItem(
          `carousel_config_${currentScene.value}`,
          JSON.stringify({
            config: configOptions,
            items: carouselItems.value,
          })
        )
      } catch (e) {
        console.error('保存到本地存储失败', e)
      }
      return
    }

    message.error('保存失败：API未实现')
  } catch (error) {
    console.error('保存配置失败:', error)
    message.error('配置保存失败，请检查网络连接')
  }
}

// 重置配置
const resetConfig = () => {
  Object.assign(configOptions, props.initialConfig)
  carouselItems.value =
    props.initialItems.length > 0
      ? [...props.initialItems]
      : [
          {
            imageUrl: 'https://hlp-lc99-1323942529.cos.ap-chongqing.myqcloud.com/carousel/ai-1.jpg',
            title: '自然风光',
            description: '探索大自然的壮丽景色',
            buttonText: '了解更多',
            buttonLink: '#',
          },
        ]
}

// API请求函数 - 获取轮播图配置
const fetchCarouselConfig = async (scene?: string): Promise<CarouselConfigDTO | null> => {
  const targetScene = scene || currentScene.value
  try {
    // 尝试从后端获取配置
    try {
      const res = await getCarouselConfig({ scene: targetScene })
      if (res.data && res.data.code === 0 && res.data.data) {
        return res.data.data
      }
    } catch (error) {
      console.warn(`后端API未实现，使用本地模拟数据(${targetScene})`, error)
      // 当后端API不可用时，返回模拟数据
      return {
        config: {
          autoplay: true,
          autoplaySpeed: 3000,
          dots: true,
          effect: 'scrollx',
        },
        items: getLocalStoredItems(targetScene) || getDefaultItemsForScene(targetScene),
      }
    }

    // 如果上述尝试失败，显示错误并返回null
    message.error('获取配置失败：API未实现')
    return null
  } catch (error) {
    console.error('获取轮播图配置失败:', error)
    message.error('获取轮播图配置失败，请检查网络连接')
    return null
  }
}

// 上传图片前的校验
const beforeUpload = (file: File, index: number) => {
  // 检查文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件!')
    return false
  }

  // 检查文件大小
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过2MB!')
    return false
  }

  // 自动上传
  handleUpload(file, index)
  return false // 阻止自动上传
}

// 处理图片上传
const handleUpload = async (file: File, index: number) => {
  try {
    // 显示上传中状态
    message.loading('图片上传中...', 0)

    // 创建FormData对象
    const formData = new FormData()
    formData.append('file', file)

    // 调用上传API
    const res = await uploadCarouselImage(formData)

    // 上传成功，关闭loading
    message.destroy()

    if (res.data && res.data.code === 0 && res.data.data) {
      // 更新轮播项的图片URL
      carouselItems.value[index].imageUrl = res.data.data.imageUrl
      message.success('图片上传成功')
    } else {
      message.error('上传失败：' + (res.data?.message || '未知错误'))
    }
  } catch (error) {
    message.destroy()
    console.error('图片上传失败:', error)
    message.error('图片上传失败，请检查网络连接')
  }
}

// 处理上传状态变化
const handleImageChange = (info: any, index: number) => {
  if (info.file.status === 'done') {
    // 已经在handleUpload中处理了成功上传的情况
  }
}

// 从本地存储获取之前保存的轮播图项
const getLocalStoredItems = (scene?: string): CarouselItem[] | null => {
  const targetScene = scene || currentScene.value
  try {
    const storedData = localStorage.getItem(`carousel_config_${targetScene}`)
    if (storedData) {
      const parsedData = JSON.parse(storedData)
      if (parsedData && Array.isArray(parsedData.items)) {
        return parsedData.items
      }
    }
    return null
  } catch (e) {
    console.error('从本地存储读取失败', e)
    return null
  }
}

// 获取指定场景的默认轮播图项
const getDefaultItemsForScene = (scene: string): CarouselItem[] => {
  if (scene === 'home') {
    return [
      {
        imageUrl: '/img/view.jpg',
        title: '自然风光',
        description: '探索大自然的壮丽景色',
        buttonText: '了解更多',
        buttonLink: '/under-development',
        scene: 'home',
      },
      {
        imageUrl: '/img/city.jpg',
        title: '城市夜景',
        description: '繁华都市的迷人夜色',
        buttonText: '查看详情',
        buttonLink: '/under-development',
        scene: 'home',
      },
      {
        imageUrl: '/img/ai.png',
        title: 'AI指导',
        description: '感受艺术带来的无限灵感',
        buttonText: '艺术展览',
        buttonLink: '/ai',
        scene: 'home',
      },
      {
        imageUrl: '/img/food.jpg',
        title: '美食探索',
        description: '品味各地美食文化',
        buttonText: '美食指南',
        buttonLink: '/under-development',
        scene: 'home',
      },
    ]
  } else if (scene === 'anime') {
    return [
      {
        imageUrl: '/img/Anime.avif',
        title: '《通往夏天的隧道，再见的出口》',
        description: '浦岛隧道',
        buttonText: '探索更多',
        buttonLink: '/under-development',
        scene: 'anime',
      },
      {
        imageUrl: '/img/Anime1.avif',
        title: '罗小黑战记',
        description: '中国动画',
        buttonText: '观看详情',
        buttonLink: '/under-development',
        scene: 'anime',
      },
      {
        imageUrl: '/img/Anime2.avif',
        title: '鬼灭之刃',
        description: '炭治郎与祢豆子',
        buttonText: '了解更多',
        buttonLink: '/under-development',
        scene: 'anime',
      },
      {
        imageUrl: '/img/Anime3.avif',
        title: '刀剑神域',
        description: '亚丝娜',
        buttonText: '查看角色',
        buttonLink: '/under-development',
        scene: 'anime',
      },
    ]
  } else {
    return [
      {
        imageUrl: '/img/view.jpg',
        title: '默认轮播项',
        description: '请添加描述',
        buttonText: '点击按钮',
        buttonLink: '#',
        scene,
      },
    ]
  }
}

// 处理场景变化
const handleSceneChange = async (scene: string) => {
  currentScene.value = scene
  emit('update:scene', scene)
  await loadConfigForScene(scene)
}

// 加载指定场景的配置
const loadConfigForScene = async (scene: string) => {
  try {
    const data = await fetchCarouselConfig(scene)
    if (data) {
      if (data.config) {
        Object.assign(configOptions, data.config)
      }
      if (data.items && Array.isArray(data.items)) {
        carouselItems.value = [...data.items]
      }
      return true
    }
  } catch (error) {
    console.error(`加载${scene}场景轮播图配置失败:`, error)
  }
  return false
}

// 暴露API函数给父组件使用
defineExpose({
  fetchCarouselConfig,
  saveConfig,
  resetConfig,
  loadConfigForScene,
  currentScene,
})

// 添加默认导出
defineOptions({
  name: 'CarouselConfigPanel',
})
</script>

<style scoped>
.carousel-config-panel {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  max-width: 800px;
  margin: 0 auto;
}

.panel-title {
  font-size: 1.5rem;
  margin-bottom: 20px;
  color: #333;
  text-align: center;
}

.slider-value {
  text-align: center;
  color: #666;
  margin-top: 5px;
}

.carousel-item-config {
  margin-bottom: 16px;
}

.item-card {
  border: 1px solid #f0f0f0;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.add-item-btn {
  margin-top: 10px;
}

.image-upload-wrapper {
  display: flex;
  align-items: center;
}

.image-preview {
  margin-top: 10px;
  margin-left: 10px;
  max-width: 200px;
  max-height: 200px;
  overflow: hidden;
  border-radius: 4px;
  border: 1px solid #f0f0f0;
}

.image-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style> 